package com.cosina.game.crystallight.engine;

import android.graphics.Point;
import android.graphics.Rect;

import com.cosina.game.crystallight.CrystalLightActivity;
import com.cosina.game.crystallight.model.crystal.Tower;
import com.cosina.game.crystallight.ui.activity.ActivityStatus;

public class TouchHandler {

	public Rect mapArea = new Rect(5,5,44*7 + 5,44*9 + 5);
	public Rect genTotalArea = new Rect(5,5 + 44*9,315,5+ 44*10);
	public Rect mixtrueArea = new Rect(5 + 44*3,5 + 44*9,320-5 -44*3,5+ 44*10);
	public void handler(int x, int y) {
		
		if(ActivityStatus.current == ActivityStatus.RUNNING){
			if(BattleEngine.status == BattleEngine.Status.defeat){
				CrystalLightActivity.self.doShowMap();
				return;
			}
			
			if(BattleEngine.status == BattleEngine.Status.victory){
				CrystalLightActivity.self.doShowMap();
				return;
			}
			
			if(mapArea.contains(x,y)){
				mapHandler(x,y);
				return;
			}
			if(mixtrueArea.contains(x,y)){
				mixtureHandler(x,y);
				return ;
			}
			if(genTotalArea.contains(x,y)){
				genHandler(x,y);
				return ;
			}
		}else{
			
		}
	}
	
	private void genHandler(int x, int y) {
		int index = -1;
		if(x<160){
			index = x/44;
		}else{
			index =  (x-55)/44;
		}
		BattleEngine.desk.boxes[index].detect();
	}
	
	private void mixtureHandler(int x, int y) {
		BattleEngine.desk.cuvette.detect();
	}

	public void mapHandler(int x, int y){
		int xIndex = (x-5)/44;
		int yIndex = (y-5)/44;
		Point[] points = BattleEngine.field.locationAbilities();
		for(int i=0; i < points.length; i++){
			if(points[i].equals(xIndex, yIndex)){
				BattleEngine.abilityManager.getContextAbilities()[i].doHandler();
				return;
			}
		}
		Point castleDoorLocation = BattleEngine.field.getCastleArea()[1];
		if(castleDoorLocation.equals(xIndex, yIndex)){
			BattleEngine.sheild.tryRepair();
			return;
		}
		Point acceralationLocation = BattleEngine.field.locationSpeed();
		if(acceralationLocation.equals(xIndex,yIndex)){
			BattleEngine.speedManager.swtich();
			return;
		}
		
		for(Point enemyArea : BattleEngine.field.getEnemyHomeArea()){
			if(enemyArea .equals(xIndex,yIndex)){
				BattleEngine.wavePanelManager.knockDoor();
				return;
			}
		}
		for(Tower tower :  BattleEngine.architect.getTowers()){
			if(tower.location.equals(xIndex,yIndex)){
				tower.detect();
				return ;
			}
		}
		
		if(BattleEngine.architect.isBuildModel()){
			BattleEngine.architect.build(xIndex, yIndex);
		}
	}
}
